package com.cskt.petoms.controller;

import com.cskt.common.entity.vo.ResultVO;
import com.cskt.common.entity.vo.StatusEnum;
import com.cskt.common.entity.vo.UserInfoVO;
import com.cskt.common.exception.BaseException;
import com.cskt.petoms.service.CartService;
import com.cskt.petoms.service.remote.RemoteUserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 购物车控制器
 *
 * @author admin
 **/
@RestController
@RequestMapping(value = "/cart")
public class CartController {
    private static final Logger log = LoggerFactory.getLogger(CartController.class);
    @Resource
    private CartService cartService;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DiscoveryClient discoveryClient;
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private RemoteUserService userService;

    private Integer index = 0;

    /**
     * 添加到购物车
     *
     * @param skuId 商品规格id
     * @param num   当前规格商品数量
     * @param token 当前登录用户token
     * @return ResultVO
     */
    @PostMapping(value = "add")
    public ResultVO<?> addCart(Long skuId, Integer num, @RequestHeader(value = "Token") String token) throws JsonProcessingException {
        //远程调用获取当前登录用户信息，调用pet-ums微服务的获取用户信息接口
        // restTemplate方案
        //HttpHeaders requestHeaders = new HttpHeaders();
        //requestHeaders.set("Token", token);
        ////将请求头封装到httpentity对象中
        //HttpEntity httpEntity = new HttpEntity(requestHeaders);
        //String url = "http://pet-ums/ums/user/getUserByToken";
        //
        ////发起远程调用，获取用户信息
        //ResultVO<UserInfoVO> resultVO = restTemplate.exchange(url, HttpMethod.GET, httpEntity, new ParameterizedTypeReference<ResultVO<UserInfoVO>>() {
        //}).getBody();
        ////log.info("来自远程服务：ip:{},port:{}，响应体：{}", serviceInstance.getHost(), serviceInstance.getPort(), objectMapper.writeValueAsString(resultVO));
        //log.info("响应体：{}",objectMapper.writeValueAsString(resultVO));
        //UserInfoVO loginUser = resultVO.getData();

        //Object loginUser = resultVO.getData();
        // OpenFeign方案
        ResultVO<UserInfoVO> resultVO = userService.getUserByToken(token);
        
        log.info("远程服务响应体：{}", objectMapper.writeValueAsString(resultVO));
        
        if (ObjectUtils.isEmpty(resultVO) || !resultVO.getCode().equals(StatusEnum.SUCCESS.getCode())) {
            log.info("远程调用pet-ums微服务异常");
            throw new BaseException(StatusEnum.FAIL_REMOTE_CALL);
        }
        
        UserInfoVO loginUser = resultVO.getData();
        if (ObjectUtils.isEmpty(loginUser)) {
            return ResultVO.error(StatusEnum.AUTH_USER_NOT_LOGIN);
        }
        cartService.addCart(skuId, num, loginUser.getId());
        //模拟 不需要验证用户
        //cartService.addCart(skuId, num, 105L);
        return ResultVO.ok();
    }

}
